package org.ala.tiktools.tools.thread_pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ala
 * @date 2025-02-20 10:45
 */
public class ThreadPoolTools {

    /**
     *  空值映射
     */
    public static ThreadPoolExecutor NULL = build(1, 1, 1, "NULL");

    /**
     *  构建线程池
     */
    public static ThreadPoolExecutor build(int coreSize, int maxSize, int queueSize, String namePrefix) {
        return new ThreadPoolExecutor(
                coreSize, maxSize,
                180, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueSize),
                new ThreadFactory() {
                    AtomicInteger cnt = new AtomicInteger();
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName(namePrefix + "_" + cnt.getAndIncrement());
                        t.setDaemon(false);
                        return t;
                    }
                }
        );
    }
}
